package com.kim.OxBridgeDada.scoring;

import com.kim.OxBridgeDada.common.ErrorCode;
import com.kim.OxBridgeDada.exception.BusinessException;
import com.kim.OxBridgeDada.model.entity.App;
import com.kim.OxBridgeDada.model.entity.UserAnswer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 *  评分策略全局执行器，方便自动执行何种评分策略
 */
@Service
public class ScoringStrategyExecutor {

    // 策略列表
    @Resource
    private List<ScoringStrategy> scoringStrategyList;

    /**
     * 评分
     *
     * @param choiceList
     * @param app
     * @return
     * @throws Exception
     */
    public UserAnswer doScore(List<String> choiceList, App app) throws Exception {
        // 获取到应用类型和评分策略
        Integer appType = app.getAppType();
        Integer appScoringStrategy = app.getScoringStrategy();
        if (appType == null || appScoringStrategy == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "应用配置有误，未找到匹配的策略");
        }
        // 根据注解获取策略
        // 遍历所有策略
        for (ScoringStrategy strategy : scoringStrategyList) {
            // 通过反射获取到某一个策略的注解
            if (strategy.getClass().isAnnotationPresent(ScoringStrategyConfig.class)){
                // 获取到对应策略类的注解
                ScoringStrategyConfig annotation = strategy.getClass().getAnnotation(ScoringStrategyConfig.class);
                // appType和scoringStrategy一致就执行对应评分策略的评分逻辑方法
                if (annotation.appType() == appType && annotation.scoringStrategy() == appScoringStrategy){
                    return strategy.doScore(choiceList, app);
                }
            }
        }

        throw new BusinessException(ErrorCode.SYSTEM_ERROR, "应用配置有误，未找到匹配的策略");
    }
}

